<template>
	<div class="goods_list_add_edit">
		<el-tabs v-model="tab" :before-leave="onTabBefore">
			<el-tab-pane :label="`基本`" name="basic">
				<basic v-if="tab" ref="basic"></basic>
			</el-tab-pane>
			<el-tab-pane :label="`详情`" name="detail">
				<detail v-if="tab" ref="detail" @detail="detail"></detail>
			</el-tab-pane>
			<el-tab-pane :label="`商品SKU`" name="sku">
				<sku v-if="tab" ref="sku"></sku>
			</el-tab-pane>
			<el-tab-pane :label="`分享设置`" name="shareSet">
				<shareSet v-if="tab" ref="shareSet"></shareSet>
			</el-tab-pane>
			<div class="btn">
				<use-affix ref="useAffix" position="bottom" :offset="58">
					<el-button :loading="formLoading" round icon="el-icon-check" class="confirm-btn"
						@click="submitForm">确定</el-button>
					<el-button round icon="el-icon-back" class="return-btn" @click="returnPage">返回</el-button>
				</use-affix>
			</div>
		</el-tabs>
		<el-backtop target=".el-tabs__content"></el-backtop>
	</div>
</template>

<script>
	import basic from './basic';
	import detail from './detail.vue';
	import sku from './sku';
	import shareSet from './share_set';
	const __name = 'wmzmall-goods';
	const __goodsCategory = 'wmzmall-goods-category';
	const __tag = 'wmzmall-goods-tag';
		const __market_level = 'wmzmall-market-level';
	export default {
		components: {
			basic,
			detail,
			sku,
			shareSet
		},
		data() {
			return {
				dataId: '',
				formLoading: false,
				tab: '',
				requestSta: false,
				tabsStorage: ''
			};
		},
		methods: {
			async loadData() {
				let category = this.$db[__goodsCategory].where({
					state: '启用'
				}).totree({
					orderby: 'sort asc',
					startWith: 'pid == ""'
				});
				let tag = this.$db[__tag].tolist({
					page: 1,
					rows: 500
				});
				let market_level_data=this.$db[__market_level].tolist({
					page: 1,
					rows: 500
				});
				let datas = await Promise.all([category, tag,market_level_data]);
				
				this.$refs.basic.setBaseData(datas);

				if (!this.dataId) {
					this.$db[__name].getsort().then(res => {
						if (res.code == 200) {
							this.requestSta = true;
							this.$refs.basic.setSort(res.datas.sort);
						}
					});
					return;
				}

				this.$func.wmzadmin.call('goods/detail', {
					goods_id: this.dataId
				}).then(res => {
					if (res.code == 200) {
						this.$refs.basic.setData(res.datas.goods);
						this.$refs.detail.setData(res.datas);
						this.$refs.sku.setData(res.datas);
						this.$refs.shareSet.setData(res.datas.goods);
						this.requestSta = true;
					}
				});
			},
			onTabBefore(activeName, oldActiveName) {
				let flag = true;

				if (!this.$refs.basic) return;

				if (!this.requestSta) {
					flag = false;
				}

				if (this.requestSta) {
					this.$refs.basic.getData((res, valid) => {
						flag = valid;

						if (!valid && this.tab != 'basic') {
							flag = true;
							this.tab = 'basic';
						}

						if (flag && activeName == 'sku') {
							this.$refs.sku.setGoods(res);
						}

						if (flag) {
							uni.setStorage({
								key: this.tabsStorage,
								data: activeName
							});

							this.$nextTick(() => {
								this.$api.scrollOnStorage('.el-tabs__content', this.$route.path + '-' +
									activeName);

								this.$api.scrollToStorage('.el-tabs__content', this.$route.path + '-' +
									activeName);

								this.$refs.useAffix.getAffixScrollBox();
							});

							return;
						}

						uni.setStorage({
							key: this.tabsStorage,
							data: oldActiveName
						});
					});
				}

				return flag;
			},
			submitForm() {
				this.formLoading = true;

				let goods = {};
				let detail = {};
				let skus = [];
				this.$refs.basic.getData((res, valid) => {
					if (!valid) {
						this.tab = 'basic';
						this.formLoading = false;
						return;
					}
					goods = res;

					this.$refs.detail.getData(async (res, valid) => {
						if (!valid) {
							this.tab = 'detail';
							this.formLoading = false;
							return;
						}

						detail.desc_mobile = res.content;
						goods.img = res.imgs[0].url;
						goods.imgs = res.imgs;
						if (res.video) {
							if (res.video.poster && res.video.poster.indexOf('blob') != -1) {
								const result = await uniCloud.uploadFile({
									filePath: res.video.poster,
									cloudPath: res.video.name.split('.')[0] + '.png'
								});
								let posterUrl = result.fileID;
								if (posterUrl.indexOf('cloud://') !== -1) {
									const urls = await uniCloud.getTempFileURL({
										fileList: [posterUrl]
									});
									if (urls.fileList && urls.fileList.length > 0) {
										posterUrl = urls.fileList[0].tempFileURL || '';
									}
								}

								res.video.poster = posterUrl;
							}
							if (res.video.url && res.video.url.indexOf('blob') != -1) {
								const result = await uniCloud.uploadFile({
									filePath: res.video.url,
									cloudPath: res.video.name
								});
								let videoUrl = result.fileID;
								if (videoUrl.indexOf('cloud://') !== -1) {
									const urls = await uniCloud.getTempFileURL({
										fileList: [videoUrl]
									});
									if (urls.fileList && urls.fileList.length > 0) {
										videoUrl = urls.fileList[0].tempFileURL || '';
									}
								}

								res.video.url = videoUrl;
							}
						}
						goods.video = res.video;
						for (const key in goods) {
							if (goods.hasOwnProperty(key)) {
								if (typeof goods[key] === 'string') {
									if (/^[0-9]*$/.test(goods[key])) {
										goods[key] = parseInt(goods[key]);
									} else if (/^[0-9]+(.[0-9]{1,3})?$/.test(goods[key])) {
										goods[key] = parseFloat(goods[key]);
									}
								}
							}
						}
						detail.desc_mobile = detail.desc_mobile.replace(/inline-/gi, '');

						this.$refs.sku.getData((skus, tables, valid) => {
							if (!valid) {
								this.tab = 'sku';
								this.formLoading = false;
								return;
							}

							goods.skus = skus;
							skus = tables;

							if (skus.length > 0) {
								let min_price;
								let min_market_price;
								let min_vip_price;
								let stock_num = 0;
								skus.forEach((x, i) => {
									if(i == 0){
										min_price = x.price;
										min_market_price = x.market_price;
										min_vip_price = x.vip_price;
									}
									
									if (x.price < min_price) {
										min_price = x.price;
									}
									
									if (x.market_price < min_market_price) {
										min_market_price = x.market_price;
									}
									
									if (x.vip_price < min_vip_price) {
										min_vip_price = x.vip_price;
									}
									
									x.img = '';
									if (x.imgObj) {
										x.img = x.imgObj.url;
									}

									stock_num += x.stock_num;
								});

								goods.price = min_price;

								goods.market_price = min_market_price;

								goods.stock_num = stock_num;

								if (goods.is_vip == '是') {
									goods.vip_price = min_vip_price;
								}
							}

							this.$refs.shareSet.getData((res, valid) => {
								if (!valid) {
									this.tab = 'shareSet';
									this.formLoading = false;
									return;
								}
								goods.share_title = res.share_title;
								goods.share_img = res.share_img;
								goods.share_desc = res.share_desc;
								goods.shop_id=uni.getStorageSync('wmzadmin_user_shop_id')

								if (!this.dataId) {
									this.$func.wmzadmin
										.call('goods/add', {
											goods,
											detail,
											skus
										})
										.then(res => {
											if (res.code == 200) {
												this.$message({
													message: res.datas.msg,
													type: 'success'
												});
												this.returnPage();
											}
											this.formLoading = false;
										});
								} else {
									this.$func.wmzadmin
										.call('goods/edit', {
											goods_id: this.dataId,
											goods,
											detail,
											skus
										})
										.then(res => {
											if (res.code == 200) {
												this.$message({
													message: res.datas.msg,
													type: 'success'
												});
												this.returnPage();
											}
											this.formLoading = false;
										});
								}
							});
						});
					});
				});
			},
			returnPage() {
				uni.$emit('closeTab');
				uni.redirectTo({
					url: '/pages/goods/list/goods_list'
				});
			}
		},
		created() {
			this.dataId = this.$route.query.id || '';
			this.tabsStorage = '__tabs' + this.$route.path;
			this.loadData();
		},
		mounted() {
			this.tab = uni.getStorageSync(this.tabsStorage) || 'basic';

			if (!this.dataId) {
				this.tab = 'basic';
				uni.removeStorageSync(this.tabsStorage);
			}

			const ele = document.querySelector('.el-tabs__content');
			let offset = this.$api.offset(ele);

			ele.style.position = 'fixed';
			ele.style.top = offset.t + 29 + 'px';
			ele.style.left = 'calc(16px + var(--window-left))';
			ele.style.bottom = '16px';
			ele.style.right = '16px';
			ele.style.overflow = 'overlay';

			this.$nextTick(() => {
				this.$api.scrollOnStorage('.el-tabs__content', this.$route.path + '-' + this.tab);

				this.$api.scrollToStorage('.el-tabs__content', this.$route.path + '-' + this.tab);
			});
		}
	};
</script>

<style>
	.goods_list_add_edit .btn {
		background-color: #fff;
		padding-left: 170px;
		margin-top: -20px;
		border-radius: 10px;
		padding-bottom: 42px;
	}

	.goods_list_add_edit>>>.el-tabs__content {
		transition: all 0.35s;
		border-radius: 10px;
	}
</style>
